/** 
 * Description:订单管理类
 * Date:2011-11-15
 * Author:Along	
*/
package com.community.shopping.web;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.community.shopping.domain.GoodsComment;
import com.community.shopping.domain.Order;
import com.community.shopping.domain.OrderItem;
import com.community.shopping.domain.User;
import com.community.shopping.service.logic.GoodsCommentManager;
import com.community.shopping.service.logic.OrderManager;
import com.community.shopping.service.logic.Page;
import com.community.shopping.service.logic.UserManager;


@Controller 
public class OrderControl {

	@Autowired  
    private OrderManager orderManager;
	
	@Autowired  
    private UserManager userManager;
	
	@Autowired  
    private GoodsCommentManager goodsCommentManager;

	private SimpleDateFormat formatDate=new SimpleDateFormat("yyyy-MM-dd");
	private SimpleDateFormat formatMonth=new SimpleDateFormat("yyyy-MM");
	private SimpleDateFormat formatNum=new SimpleDateFormat("yyyyMMdd");
	private SimpleDateFormat formatLong=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	
	@RequestMapping("/admin/queryorder")
	public  ModelAndView queryallOrder(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		ModelAndView mav = new ModelAndView("orderlist.jsp");    
		String status=request.getParameter("status");	
		if(StringUtils.isBlank(status))
		{
			status="5,10,15";//默认查询下达状态的订单
		}		
		String beginDate=request.getParameter("beginDate");
		if(beginDate==null||"".equals(beginDate))
		{
			beginDate=formatNum.format(new Date());
		}else
		{
			beginDate=beginDate.replaceAll("-", "");
		}
		beginDate=beginDate+"0000";
		String endDate=request.getParameter("endDate");
		if(endDate==null||"".equals(endDate))
		{
			endDate=formatNum.format(new Date());
		}else
		{
			endDate=endDate.replaceAll("-", "");
		}
		endDate=endDate+"9999";
		String filter=" orderno > '"+beginDate+"' and orderno < '"+endDate+"' and status in ("+status+") ";
		
		String orderno=request.getParameter("orderno");
		if(orderno!=null&&!"".equals(orderno))
		{
			filter=filter+" and orderNo='"+orderno+"'";
		}
        List allOrders=orderManager.queryOrder(filter);
        mav.addObject("orders", allOrders);
        /*String[] price=orderManager.sumOrder(filter).split("_");
        if(price[0]!=null && !"null".equalsIgnoreCase(price[0]))
        {
        mav.addObject("sumprice", price[0]);
        mav.addObject("sumcostprice", price[1]);
        mav.addObject("profit", Float.parseFloat(price[0])-Float.parseFloat(price[1]));
        }*/
        return mav;
	}
	
	@RequestMapping("/admin/saveorder")
	public  ModelAndView changeOrder(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String orderId=request.getParameter("orderId");	
		String tostatus=request.getParameter("tostatus");
		orderManager.saveOrder(orderManager.queryOrderById(orderId), Integer.valueOf(tostatus)); 
        return queryallOrder(request,response);
	}
	
	/**
	 * 保存订单的方法
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/order/save")
	public void saveOrder(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String memo=request.getParameter("memo");
		memo=java.net.URLDecoder.decode(memo, "UTF-8");  
		String userId=request.getParameter("userId");
		User user=userManager.getUserById(userId);
		String cookie=request.getParameter("cookie");
		String info=orderManager.saveOrderByCookie(user,cookie,memo);
        response.getWriter().print(info); 	
	}
	

	/**
	 * 查询当前用户的订单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/order/query")
	public void queryOrder(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String userId=request.getParameter("userId");
		String time=request.getParameter("time");
		String filter="";
		if("today".equals(time))
		{
			filter=" createDate like '"+formatDate.format(new Date())+"%' and orderUser.id="+userId;
		}else if("month".equals(time))
		{
			filter=" createDate like '"+formatMonth.format(new Date())+"%' and orderUser.id="+userId;
		}else if("all".equals(time))
		{
			filter=" orderUser.id="+userId;
		}
		Page page=new Page(request,8);	
		List<Order> Orders=orderManager.queryOrder(filter,page);
		StringBuilder sb=new StringBuilder("{\"orders\":[");
		for(Order order:Orders)
		{
			if(sb.length()>20)
			{
				sb.append(",");	
			}
			sb.append("{");
			sb.append("\"id\":\""+order.getId()+"\",");
			sb.append("\"no\":\""+order.getOrderNo()+"\",");
			sb.append("\"price\":\""+order.getTotalPrice()+"\",");
			sb.append("\"createdate\":\""+order.getCreateDate()+"\",");
			sb.append("\"yf\":\""+order.getYfPrice()+"\",");
			sb.append("\"ifcomment\":\""+order.getIfComment()+"\",");
			sb.append("\"status\":\""+order.getStatus()+"\"");
			sb.append("}");		
		}
		sb.append("],\"pageno\":\""+page.getCurrentPage()+"\",\"totalpage\":\""+page.getTotalPages()
				+"\",\"totalsize\":\""+page.getTotalRowsAmount()+"\"}");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString()); 			
	}
	
	
	/**
	 * 查询订单详情
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/order/querydetail")
	public void queryOrderDetail(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String orderId=request.getParameter("orderId");		
		Order order=orderManager.queryOrderById(orderId);
		StringBuilder detail=new StringBuilder("[");
		for(OrderItem orderItem:order.getOrderList())
		{
			if(detail.length()>1)
			{
				detail.append(",");	
			}
			detail.append("{");
			detail.append("\"goodsid\":\""+orderItem.getGoodsId()+"\",");
			detail.append("\"name\":\""+orderItem.getGoodsName()+"\",");
			detail.append("\"price\":\""+orderItem.getPrice()+"\",");
			detail.append("\"goodsno\":\""+orderItem.getGoodsCode()+"\",");
			detail.append("\"num\":\""+orderItem.getNum()+"\",");
			detail.append("\"kind\":\""+orderItem.getKind()+"\",");
			detail.append("\"score\":\""+orderItem.getScore()+"\",");
			detail.append("\"totalscore\":\""+orderItem.getTotalScore()+"\",");
			detail.append("\"totalprice\":\""+orderItem.getTotalPrice()+"\"");
			detail.append("}");		
		}
		detail.append("]");
		
		StringBuilder sb=new StringBuilder("{");
		sb.append("\"order\":{");
		sb.append("\"orderno\":\""+order.getOrderNo()+"\",");
		sb.append("\"relname\":\""+order.getReceiveUser()+"\",");
		sb.append("\"tel\":\""+order.getReceiveContact()+"\",");
		sb.append("\"score\":\""+order.getScore()+"\",");
		sb.append("\"status\":\""+order.getStatus()+"\",");
		sb.append("\"yf\":\""+order.getYfPrice()+"\",");
		sb.append("\"address\":\""+order.getReceiveAddress()+"\",");
		sb.append("\"memo\":\""+order.getDescription()+"\",");
		sb.append("\"price\":\""+order.getTotalPrice()+"\"");
		sb.append("},\"orderDetail\":");
		sb.append(detail);
		sb.append("}");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString()); 			
	}
	
	/**
	 * 查询一条用户的返利
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/query/backsum")
	public void queryreback(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String userId=request.getParameter("userId");
		String filter=" orderUser.id ="+userId+" and status=20 ";	
		String reInfo=orderManager.queryRebackSum(filter);
		response.getWriter().print(reInfo); 			
	}
	
	/**
	 * 查询所有用户的返利
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/query/backsumall")
	public void queryrebackall(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String userId=request.getParameter("userId");
		String filter=" orderUser.id in ("+userId+") and status=20 ";	
		String reInfo=orderManager.queryRebackSum(filter);
		response.getWriter().print(reInfo); 			
	}
	
	/**
	 * 保存订单商品评价
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/order/savecomment")
	public void saveComment(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String userId=request.getParameter("userId");
		User user=userManager.getUserById(userId);
		String commentinfo=request.getParameter("commentinfo");		
		goodsCommentManager.saveComment(user, commentinfo);
		String orderId=request.getParameter("orderId");		
		Order order=orderManager.queryOrderById(orderId);
		orderManager.saveOrderScore(order);
	}

	
	/**
	 * 手机提醒查询未完成的订单
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/order/myquery")
	public void queryNewOrder(HttpServletRequest request,HttpServletResponse response)throws Exception
	{

		String filter=" createDate like '"+formatDate.format(new Date())+"%' and status=5";
		List<Order> Orders=orderManager.queryOrder(filter);
		StringBuilder sb=new StringBuilder("");
		for(Order order:Orders)
		{
			if(sb.length()>1)
			{
				sb.append(",");	
			}
			sb.append(order.getOrderNo().substring(8,10)+","+order.getReceiveUser()+","+"￥"+order.getTotalPrice()+","
					+order.getReceiveAddress()+","+order.getDescription());			
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString()); 			
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/location/insert")
	public void locationInsert(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String x=request.getParameter("x");
		String y=request.getParameter("y");
		String context=formatLong.format(new Date())+","+x+","+y+"|";
		String systemBase=request.getSession().getServletContext().getRealPath("/");
		 //检查目录存不存在	
		String locationFilePath=systemBase+"location"+File.separatorChar+"location.txt";
		appendFile(locationFilePath,context);
	}
	
	 /**
     * 方法追加文件：使用FileWriter
     */
    public static void appendFile(String fileName, String content) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(fileName, true);
            writer.write(content);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
